import Vue from 'vue'
import VueRouter from 'vue-router'
import { Message } from 'element-ui'

Vue.use(VueRouter)
Vue.component(Message.name, Message)

// 将login、home、welcome组合到相同的异步块中，以下同理
const login = () =>
  import(
    /* webpackChunkName: "login_home_welcome" */ '../components/Login.vue'
  )

const home = () =>
  import(/* webpackChunkName: "login_home_welcome" */ '../views/Home.vue')

const welcome = () =>
  import(
    /* webpackChunkName: "login_home_welcome" */ '../components/Welcome.vue'
  )

const User = () =>
  import(
    /* webpackChunkName: "uers_rights_roles" */ '../components/users/User.vue'
  )

const GoodsCategory = () =>
  import(
    /* webpackChunkName: "uers_rights_roles" */ '../components/goods/GoodsCategory.vue'
  )

const GoodsCategoryParam = () =>
 import(
   /* webpackChunkName: "uers_rights_roles" */ '../components/goods/GoodsCategoryParam.vue'
 )

const Goods= () =>
 import(
   /* webpackChunkName: " " */ '../components/goods/Goods.vue'
 )

const GoodsAdd = () =>
import(
  /* webpackChunkName: "" */ '../components/goods/GoodsAdd.vue'
)


// 防止同一路由多次点击报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 后台管理系统，除了登录页面不需要token，其他页面都需要token
const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    component: login,
  },
  {
    path: '/home',
    component: home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: welcome,
      },
      {
        path: '/User',
        component: User,
      },
      {
        path: '/GoodsCategory',
        component: GoodsCategory,
      },
      {
        path: '/GoodsCategoryParam',
        component: GoodsCategoryParam,
      },
      {
        path: '/Goods',
        component: Goods,
      },
      {
        path: '/Good/GoodsAdd',
        component: GoodsAdd,
      }

    ],
  },
]


//1.定义路由对象
const router = new VueRouter({
  routes
})


 //  2.定义导航守卫(注意位置)
 //   beforeEach: 循环遍历用户的所有的请求.(拦截)
 //               在其中需要定义一个回调函数(3个参数)
 //  参数介绍:  to :要访问的请求路径
 //            from: 从哪个页面跳转而来
 //            next: 表示请求放行
 //业务需求: 1.如果用户请求/login
 //         2.如果不是login则判断是否登录 token
router.beforeEach((to,from,next) => {
    if(to.path === '/login') return next()
    //2.获取token信息
    let token = localStorage.getItem('token')
    //3.判断token是否有数据??  if(token) 如果token不为null
    //如果token为null 则跳转到登录页面
    if(!token) return next('/login')
    //表示放行
    next()

})






export default router

// 后台管理系统，除了登录页面不需要token，其他页面都需要token
/**
 * 1 如果要去的是登录页面 直接跳转
 * 2 如果不是，判断缓存有没有token
 *  1 有 跳转
 *  2 没有 重新登录获取
 */
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  if (localStorage.getItem('token')) {
    next()
  } else {
    Message.info('请登录')
    setTimeout(() => {
      next('/login')
    }, 1000)
  }
})
